package com.wbf.demo.security;

import com.alibaba.fastjson.JSONObject;
import com.wbf.demo.security.exception.IllegalPasswordFormatException;
import com.wbf.demo.security.exception.IllegalUsernameFormatFormatException;
import com.wbf.demo.util.RequestUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: security_demo
 * @description: 用户名密码登陆拦截器
 * 和默认的UsernamePasswordAuthenticationFilter相同
 * 增加参数格式验证的功能
 * 用户名密码登录
 * @author: guangdao
 * @create: 2022-04-14 18:16
 **/
public class VerifyUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public VerifyUsernamePasswordAuthenticationFilter(String filterProcessesUrl) {
        super(new AntPathRequestMatcher(filterProcessesUrl, "POST"));
    }

    public VerifyUsernamePasswordAuthenticationFilter() {
        super(new AntPathRequestMatcher("/login/username", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException {
        JSONObject jsonObject = JSONObject.parseObject(RequestUtils.getRequestPostStr(request));
        //验证手机号
        String username = jsonObject.getString("username");
        if (username == null){
            throw new IllegalUsernameFormatFormatException();
        }

        //验证密码
        String password = jsonObject.getString("password");
        if (password == null){
            throw new IllegalPasswordFormatException("password:" + password);
        }
        UserNamePassWordRegisterToken authRequest = new UserNamePassWordRegisterToken(username, password);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

}
